﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using ComicIsland.App.CIHelper;
using ComicIsland.App.Resources;
using ComicIsland.Common;
using ComicIsland.Common.Entities;
using ComicIsland.Common.Entities.ComicDatabase;
using ComicIsland.Common.Entities.InterfaceJson;
using ComicIsland.Common.StorageHelper;
using ComicIsland.Common.WebHelper;
using Microsoft.Phone.BackgroundTransfer;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;

namespace ComicIsland.App.Views.DownloadComicViews
{
    public partial class DownloadQueuePage : PhoneApplicationPage
    {
        private bool IsNeedReloadData = false;
        private int comicId = 0;
        private BackgroundTransferHelper btHelper;
        private bool IsRefreshUI = true;

        public DownloadQueuePage()
        {
            InitializeComponent();
            this.IsNeedReloadData = true;
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            IsRefreshUI = true;
            //
            if (base.NavigationContext.QueryString.ContainsKey("comicId"))
            {
                string paramComicId = string.Empty;
                base.NavigationContext.QueryString.TryGetValue("comicId", out paramComicId);
                int.TryParse(paramComicId, out comicId);
                if (comicId <= 0)
                {
                    base.NavigationService.GoBack();
                    return;
                }
            }
            //加载下载过的漫画列表
            if (this.IsNeedReloadData)
            {
                LoadDownloadQueueComicChapters();
            }

            WaitCallback callback = new WaitCallback(this.ThreadTransfer);
            ThreadPool.QueueUserWorkItem(callback);
            //Task.Run(() =>
            //{
            //    this.btHelper = new BackgroundTransferHelper();
            //    this.btHelper.OnBackgroundTransferStatus += btHelper_OnBackgroundTransferStatus;
            //    this.btHelper.InitDownloadQueue(comicId);
            //});
            base.OnNavigatedTo(e);
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            IsRefreshUI = false;
            base.OnNavigatedFrom(e);
        }

        void ThreadTransfer(object o)
        {
            this.btHelper = new BackgroundTransferHelper();
            this.btHelper.OnBackgroundTransferStatus += btHelper_OnBackgroundTransferStatus;
            this.btHelper.InitDownloadQueue(comicId);
        }

        private void pivot_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (this.pivotFinishedChapter == this.pivot.SelectedItem)
            {
                ApplicationBar = (ApplicationBar)Resources["appbarPivotFinished"];
            }
            else if (this.pivotAllChapter == this.pivot.SelectedItem)
            {
                ApplicationBar = (ApplicationBar)Resources["appbarPivotAll"];
            }
        }

        void UpdateGrid(Grid grid, DbChapter dbChapter)
        {
            foreach (UIElement element in grid.Children)
            {
                if (element == null)
                    continue;
                if (element is ProgressBar)
                {
                    var el = element as ProgressBar;
                    if (el == null)
                        continue;
                    el.Value = GetDonwloadStatusProgress(dbChapter.ComicIdAndPartId);
                }
                else if (element is StackPanel)
                {
                    var el = element as StackPanel;
                    if (!(el != null && el.Children != null && el.Children.Count > 0))
                        continue;
                    foreach (UIElement sp in el.Children)
                    {
                        if (sp == null)
                            continue;
                        var txt = sp as TextBlock;
                        if (txt == null)
                            continue;
                        if (txt.Name.Equals("txtCurrentTotal"))
                        {
                            txt.Text = GetDownloadCurrentImages(dbChapter.ComicIdAndPartId).ToString();
                        }
                        else if (txt.Name.Equals("txtTotalCount"))
                        {
                            txt.Text = GetDownloadTotalImages(dbChapter.ComicIdAndPartId).ToString();
                        }
                        else if (txt.Name.Equals("txtStatusInfo"))
                        {
                            txt.Text = GetDownloadStatusInfo(dbChapter.ComicIdAndPartId);
                        }
                    }
                }
                else if (element is HyperlinkButton)
                {
                    var el = element as HyperlinkButton;
                    if (el == null)
                        continue;
                    string statusInfo = GetDownloadStatusInfo(dbChapter.ComicIdAndPartId);
                    if (AppResources.DownQueueStatusWaitDown.Equals(statusInfo))
                        el.Content = AppResources.DownQueueOperateDelete;
                    else if (AppResources.DownQueueStatusDownloading.Equals(statusInfo))
                        el.Content = AppResources.DownQueueOperatePause;
                    else if (AppResources.DownQueueStatusCompleted.Equals(statusInfo))
                        el.Content = AppResources.DownQueueOperateRead;
                    else if (AppResources.DownQueueStatusPause.Equals(statusInfo))
                        el.Content = AppResources.DownQueueOperateDown;
                }
            }
        }

        void btHelper_OnBackgroundTransferStatus(DbImage dbImage)
        {
            //更新对应章节的状态
            if (dbImage == null)
                return;

            var grids = Helper.FindChildren<Grid>(this.llsAll);
            if (!(grids != null && grids.Count() > 0))
                return;
            foreach (Grid grid in grids)
            {
                if (grid == null)
                    continue;

                DbChapter dbChapter = grid.DataContext as DbChapter;
                if (dbChapter == null)
                    continue;
                if (!dbChapter.ComicIdAndPartId.Equals(dbImage.ComicIdAndPartId))
                    continue;
                if (!(grid != null && grid.Children != null && grid.Children.Count > 0))
                    continue;
                //
                if (IsRefreshUI)
                    UpdateGrid(grid, dbChapter);
                //break;
            }

        }

        #region ********************更新下载状态信息******************************
        private double GetDonwloadStatusProgress(string paramComicAndPartId)
        {
            double result = 0.00;
            try
            {
                string comicAndPartId = string.Empty;
                if (paramComicAndPartId != null)
                {
                    comicAndPartId = paramComicAndPartId.ToString();
                }

                if (!string.IsNullOrWhiteSpace(comicAndPartId))
                {
                    var cpIds = comicAndPartId.Split('#');
                    if (cpIds != null && cpIds.Length == 2)
                    {
                        int comicId = 0, partId = 0;
                        int.TryParse(cpIds[0], out comicId);
                        int.TryParse(cpIds[1], out partId);

                        var items = App.comicDbHelper.ImageGetByComicIdAndChapterId(comicId, partId);
                        if (items != null && items.Count > 0)
                        {
                            int totalCompleted = items.Where<DbImage>(p => DownloadComicChapterStatus.Completed.ToString().Equals(p.DownloadStatus)).Count();
                            result = ((totalCompleted * 1.00) / (items.Count * 1.00)) * 100.00;
                        }
                    }
                }
            }
            catch (Exception err)
            {
                LogHelper.LogError(err.Message, this.GetType(), MethodBase.GetCurrentMethod());
            }
            LogHelper.LogInfo("progress:\t" + result, this.GetType(), MethodBase.GetCurrentMethod());
            return result;
        }

        private string GetDownloadStatusInfo(string paramComicAndPartId)
        {
            string result = AppResources.DownQueueStatusWaitDown;
            if (string.IsNullOrWhiteSpace(paramComicAndPartId))
                return result;
            var cpIds = paramComicAndPartId.Split('#');
            if (cpIds != null && cpIds.Length == 2)
            {
                int comicId = 0, partId = 0;
                int.TryParse(cpIds[0], out comicId);
                int.TryParse(cpIds[1], out partId);

                var items = App.comicDbHelper.ImageGetByComicIdAndChapterId(comicId, partId);
                if (items != null && items.Count > 0)
                {
                    int completedTotal = items.Where(p => DownloadComicChapterStatus.Completed.ToString().Equals(p.DownloadStatus)).Count();
                    if (items.Count == completedTotal)
                        result = AppResources.DownQueueStatusCompleted;
                    else
                        result = AppResources.DownQueueStatusDownloading;
                }
            }

            return result;
        }

        private int GetDownloadTotalImages(string paramComicAndPartId)
        {
            int total = 0;
            if (string.IsNullOrWhiteSpace(paramComicAndPartId))
                return total;

            var cpIds = paramComicAndPartId.Split('#');
            if (cpIds != null && cpIds.Length == 2)
            {
                int comicId = 0, partId = 0;
                int.TryParse(cpIds[0], out comicId);
                int.TryParse(cpIds[1], out partId);

                var items = App.comicDbHelper.ImageGetByComicIdAndChapterId(comicId, partId);
                if (items != null && items.Count > 0)
                    total = items.Count;
            }
            return total;
        }

        private int GetDownloadCurrentImages(string paramComicAndPartId)
        {
            int total = 0;
            if (string.IsNullOrWhiteSpace(paramComicAndPartId))
                return total;
            var cpIds = paramComicAndPartId.Split('#');
            if (cpIds != null && cpIds.Length == 2)
            {
                int comicId = 0, partId = 0;
                int.TryParse(cpIds[0], out comicId);
                int.TryParse(cpIds[1], out partId);

                var items = App.comicDbHelper.ImageGetByComicIdAndChapterId(comicId, partId);
                if (items != null && items.Count > 0)
                {
                    total = items.Where(p => DownloadComicChapterStatus.Completed.ToString().Equals(p.DownloadStatus)).Count();
                }
            }

            return total;
        }
        #endregion ********************更新下载状态信息******************************


        #region ******************************加载数据******************************
        /// <summary>
        /// 加载漫画的所有章节
        /// </summary>
        void LoadDownloadQueueComicChapters()
        {
            var localCacheItems = App.comicDbHelper.ChapterGetObservableCollectionByComic(comicId);
            if (!(localCacheItems != null && localCacheItems.Count > 0))
            {
                return;
            }
            //全部章节
            this.llsAll.ItemsSource = localCacheItems;
            this.pivotAllChapter.Header = string.Format("全部({0})", this.llsAll.ItemsSource != null ? this.llsAll.ItemsSource.Count.ToString() : "0");
            //已完成的章节
            var itemsFinished = (from p in localCacheItems where p.DownloadStatus.Equals(DownloadComicChapterStatus.Completed.ToString()) select p).OrderBy(p => p.PartId).ToList<DbChapter>();
            if (itemsFinished != null && itemsFinished.Count > 0)
            {
                var ocItemsFinished = new ObservableCollection<DbChapter>(itemsFinished);
                this.llsFinished.ItemsSource = ocItemsFinished;
            }
            this.pivotFinishedChapter.Header = string.Format("已完成({0})", this.llsFinished.ItemsSource != null ? this.llsFinished.ItemsSource.Count.ToString() : "0");
            //下载中章节
            //var itemsDownloading = (from p in localCacheItems where p.DownloadStatus.Equals(DownloadComicChapterStatus.Downloading.ToString()) select p).ToList<DbChapter>();
            //if (itemsDownloading != null && itemsDownloading.Count > 0)
            //{
            //    var ocItemsDownloadingd = new ObservableCollection<DbChapter>(itemsDownloading);
            //    this.llsAllDownloading.ItemsSource = ocItemsDownloadingd;
            //}
            //this.pivotDownloadingChapter.Header = string.Format("下载中({0})", this.llsAllDownloading.ItemsSource != null ? this.llsAllDownloading.ItemsSource.Count.ToString() : "0");
        }
        #endregion ******************************加载数据******************************

        #region ******************************全部队列******************************
        private void llsAll_ItemRealized(object sender, ItemRealizationEventArgs e)
        {
            //if (e.ItemKind != LongListSelectorItemKind.Item)
            //    return;
            //var container = e.Container;
            //var currentSelectedItem = e.Container.Content as DbChapter;
            //if (currentSelectedItem == null)
            //    return;
            //try
            //{
            //    var grids = Helper.FindChildren<Grid>(this.llsAll);
            //    if (!(grids != null && grids.Count() > 0))
            //        return;
            //    foreach (Grid grid in grids)
            //    {
            //        if (!(grid != null && grid.Children.Count > 0))
            //            continue;
            //        this.UpdateGrid(grid, currentSelectedItem);
            //        //break;
            //    }
            //}
            //catch (Exception err)
            //{

            //}
        }

        private void lbtnOperation_Click(object sender, RoutedEventArgs e)
        {
            HyperlinkButton hlbtn = sender as HyperlinkButton;
            if (hlbtn == null)
                return;
            string statusInfo = hlbtn.Content != null ? hlbtn.Content.ToString() : string.Empty;
            if (string.IsNullOrWhiteSpace(statusInfo))
                return;
            DbChapter dbChapter = hlbtn.DataContext as DbChapter;
            if (dbChapter == null)
                return;
            if (AppResources.DownQueueOperateDelete.Equals(statusInfo))
            {
            }
            else if (AppResources.DownQueueOperatePause.Equals(statusInfo))
            {
            }
            else if (AppResources.DownQueueOperateDown.Equals(statusInfo))
            {
            }
            else if (AppResources.DownQueueOperateRead.Equals(statusInfo))
            {
                NaviService.Navigate(ComicIslandPage.RCComicReaderPage, string.Concat("?comicId=", dbChapter.ComicId, "&comicPartId=", dbChapter.PartId));
            }
        }

        private void llsAll_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }
        #endregion ******************************全部队列******************************



        private void imageOperator_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            Image image = sender as Image;
            if (image == null)
                return;
            if (image.Tag == null)
                return;
            string imageName = Convert.ToString(image.Tag);
            if (string.IsNullOrWhiteSpace(imageName))
                return;
            DbChapter dbChapter = image.DataContext as DbChapter;
            if (dbChapter == null)
                return;
            //缓存
            //string key = string.Format(KEYS.CACHEDOWNLOAD_CHAPTER_IMAGE_QUEUE, dbImage.ComicId,dbImage.PartId);
            //
            if (imageName.EndsWith("download.png"))//下载
            {
            }
            else if (imageName.EndsWith("play.png"))
            {
                NaviService.Navigate(ComicIslandPage.RCComicReaderPage, string.Concat("?comicId=", dbChapter.ComicId, "&comicPartId=", dbChapter.PartId));
            }
        }

        private void appBarSelectAll_Click(object sender, EventArgs e)
        {

        }

        private void appBarDelete_Click(object sender, EventArgs e)
        {

        }

        private void appBarPause_Click(object sender, EventArgs e)
        {

        }

        private void appBarDownload_Click(object sender, EventArgs e)
        {

        }


        #region ******************************已完成队列******************************
        private void llsFinished_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        private void appbarFinishedCheckAll_Click(object sender, EventArgs e)
        {
            var appBarIcon = sender as ApplicationBarIconButton;
            if (appBarIcon == null)
                return;

            this.Dispatcher.BeginInvoke(() =>
            {
                if ("全选".Equals(appBarIcon.Text))
                {
                    appBarIcon.Text = "取消";
                    appBarIcon.IconUri = new Uri("/Images/Icons/uncheckedall.png", UriKind.Relative);
                    this.llsFinished.IsSelectionEnabled = true;
                    foreach (var item in this.llsFinished.ItemsSource)
                    {
                        var container = this.llsFinished.ContainerFromItem(item) as LongListMultiSelectorItem;
                        if (container != null) container.IsSelected = true;
                    }
                }
                else
                {
                    appBarIcon.Text = "全选";
                    appBarIcon.IconUri = new Uri("/Images/Icons/checkedall.png", UriKind.Relative);
                    this.llsFinished.IsSelectionEnabled = false;
                }
            });
        }

        private void appbarFinishedDelete_Click(object sender, EventArgs e)
        {

        }
        #endregion ******************************已完成队列******************************





    }
}